﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;

namespace EcologyFuture.DataCollection
{
  using EcologyFuture.Helper;
  /// <summary>
  /// <c>YahooWeatherDataCollector</c> collects data from weather.yahoo.com.
  /// </summary>
  class YahooWeatherDataCollector : IDataCollector
  {
    /// <summary>
    /// Collects data from weather.yahoo.com in xml format and converts it to <c>WeatherInfo</c>.
    /// </summary>
    /// <returns><c>WeatherInfo</c> struct with weather information from weather.yahoo.com.</returns>
    public WeatherInfo CollectData()
    {
      try
      {
        Stream xmlStream = WebHelper.GetDataFromUri("http://weather.yahooapis.com/forecastrss?w=939628&u=c");
        return GetWeather(xmlStream);
      }
      catch(Exception)
      {
          throw (new EFExeption("YahooWeather collection data exeption was throwed"));
      }
    }
    /// <summary>
    /// Converts weather info from Yahoo xml format to internal <c>WeatherInfo</c> format.
    /// </summary>
    /// <param name="yahooXmlStream">Stream with xml data about the weather.</param>
    /// <returns>Weather information in <c>WeatherInfo</c> struct.</returns>
    WeatherInfo GetWeather(Stream yahooXmlStream)
    {
      WeatherInfo yahooWeather = new WeatherInfo();
      XmlReader reader;
      try
      {
        reader = XmlReader.Create(yahooXmlStream);
        reader.ReadToFollowing("lastBuildDate");
        yahooWeather.date = DateTimeHelper.ParseDate(reader.ReadString());

        reader.ReadToFollowing("yweather:location");
        yahooWeather.country = reader.GetAttribute("country");
        yahooWeather.city = reader.GetAttribute("city");
        reader.ReadToFollowing("yweather:wind");
        yahooWeather.direction = Convert.ToInt32(reader.GetAttribute("direction"));
        string strBuf = reader.GetAttribute("speed");
        yahooWeather.speed = Convert.ToSingle(strBuf.Replace('.', ',')) * 1000f / 3600.0f;
        reader.ReadToFollowing("yweather:atmosphere");
        yahooWeather.humidity = Convert.ToInt32(reader.GetAttribute("humidity"));
        strBuf = reader.GetAttribute("pressure");
        yahooWeather.pressure = Convert.ToSingle(strBuf.Replace('.', ',')) / 1000f * 750.06f;
        reader.ReadToFollowing("yweather:condition");
        yahooWeather.temperature = Convert.ToInt32(reader.GetAttribute("temp"));
      }
      catch (XmlException e)
      {
        Console.WriteLine("Xml exeption was throwed: " + e.Message);
        throw (new EFExeption());
      }
      catch (Exception e)
      {
          throw (new EFExeption("An exeption was throwed..." + e.Message));
      }
          
      return yahooWeather;
    }
  }
}
